package com.springboot.springboot3.Controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName:
 * @author: CKC
 * @DateTime: 2021/1/30 8:44
 */

@Slf4j
@Controller
public class UploadController {
    /**
     * MultipartFile  自动封装上传过来的文件
     *
     * @param email
     * @param username
     * @param headerImg
     * @param photos
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("email") String email,
                         @RequestParam("username") String username,
                         @RequestPart("headerImg") MultipartFile headerImg,
                         @RequestPart("photos") MultipartFile[] photos/**多文件上传*/,
                         HttpServletRequest request) throws IOException {
        log.info("上传信息: email={},username={},headerImg={},photos={}",
                email, username, headerImg.getSize(), photos.length);
        if (!headerImg.isEmpty()) {
            //保存到文件服务器
            String filename = UUID.randomUUID() + headerImg.getOriginalFilename();
            System.out.println(filename+":"+headerImg.getSize()/1024+"KB");
            
            headerImg.transferTo(new File("E:\\uploadTest\\"+filename));
        }
        
        System.out.println("----------------------");
        if (photos.length>0){
            for (MultipartFile photo : photos) {
                String filename = UUID.randomUUID() + photo.getOriginalFilename();
                if(!photo.isEmpty()){
                    System.out.println(filename+":"+photo.getSize()/1024+"KB");
                    photo.transferTo(new File("E:\\uploadTest\\"+filename));
                }
            }
        }
        request.setAttribute("msg", "成功");
        return "Aaa";
    }
}
